#include "filecontextmenu.h"
#include "mainwindow.h"
#include <QMessageBox>
#include <QFileInfo>
#include <QDir>
#include <QInputDialog>
#include <QAbstractItemView>
#include <QTimer>

FileContextMenu::FileContextMenu(MainWindow *mainWindow, QFileSystemModel *model, QWidget *parent)
    : QMenu(parent), m_mainWindow(mainWindow), m_model(model), m_isCutOperation(false), m_currentView(nullptr)
{
    initActions();
}

void FileContextMenu::initActions()
{
    // 1. 基础操作组
    m_openAction = addAction("打开");
    m_openAction->setShortcut(QKeySequence::Open);
    m_openAction->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton));
    addSeparator();

    // 2. 编辑操作组
    m_cutAction = addAction("剪切");
    m_cutAction->setShortcut(QKeySequence::Cut);
    m_cutAction->setIcon(style()->standardIcon(QStyle::SP_DialogDiscardButton));
    m_copyAction = addAction("复制");
    m_copyAction->setShortcut(QKeySequence::Copy);
    m_copyAction->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton));
    m_pasteAction = addAction("粘贴");
    m_pasteAction->setShortcut(QKeySequence::Paste);
    m_pasteAction->setIcon(style()->standardIcon(QStyle::SP_DialogApplyButton));

    addSeparator();

    m_deleteAction = addAction("删除");
    m_deleteAction->setShortcut(QKeySequence::Delete);
    m_deleteAction->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
    m_deleteAction->setShortcut(QKeySequence::Delete);
    m_renameAction = addAction("重命名");
    m_renameAction->setShortcut(QKeySequence::Replace);

    addSeparator();

    // 3. 新建操作组
    m_newFolderAction = addAction("新建文件夹");
    m_newFolderAction->setShortcut(QKeySequence::New);
    m_newFolderAction->setIcon(style()->standardIcon(QStyle::SP_DirIcon));

    addSeparator();

    // 4. 属性查看组
    m_propertiesAction = addAction("属性");

    // 5.全选
    m_selectAllAction = addAction("全选");
    m_selectAllAction->setShortcut(QKeySequence::SelectAll);

    // 连接信号槽
    connect(m_openAction, &QAction::triggered, this, &FileContextMenu::onOpenTriggered);
    connect(m_cutAction, &QAction::triggered, this, &FileContextMenu::onCutTriggered);
    connect(m_copyAction, &QAction::triggered, this, &FileContextMenu::onCopyTriggered);
    connect(m_pasteAction, &QAction::triggered, this, &FileContextMenu::onPasteTriggered);
    connect(m_deleteAction, &QAction::triggered, this, &FileContextMenu::onDeleteTriggered);
    connect(m_renameAction, &QAction::triggered, this, &FileContextMenu::onRenameTriggered);
    connect(m_newFolderAction, &QAction::triggered, this, &FileContextMenu::onNewFolderTriggered);
    connect(m_propertiesAction, &QAction::triggered, this, &FileContextMenu::onPropertiesTriggered);
}


QAction* FileContextMenu::showMenu(QWidget *view, const QPoint &pos)
{
    // 保存当前视图
    m_currentView = view;

    // 获取视图中的索引
    QModelIndex index = qobject_cast<QAbstractItemView*>(view)->indexAt(pos);
    bool hasValidIndex = index.isValid();

    // 更新菜单项状态
    m_openAction->setEnabled(hasValidIndex);
    m_cutAction->setEnabled(hasValidIndex);
    m_copyAction->setEnabled(hasValidIndex);
    m_deleteAction->setEnabled(hasValidIndex);
    m_renameAction->setEnabled(hasValidIndex);
    m_propertiesAction->setEnabled(hasValidIndex);
    m_pasteAction->setEnabled(view->isEnabled() && !m_copiedPath.isEmpty());

    // 保存当前索引
    setCurrentIndex(index);

    // 显示菜单并返回选中的动作
    return exec(view->mapToGlobal(pos));
}

void FileContextMenu::setCurrentIndex(const QModelIndex &index)
{
    m_currentIndex = index;
}

QModelIndex FileContextMenu::currentIndex() const
{
    return m_currentIndex;
}

void FileContextMenu::setCurrentView(QWidget *view) {
    this->m_currentView = view;
}

void FileContextMenu::onOpenTriggered()
{
    if (!m_currentIndex.isValid()) return;

    QString filePath = m_model->filePath(m_currentIndex);
    QFileInfo fileInfo(filePath);

    if (fileInfo.isDir()) {
        m_mainWindow->viewUpdated(m_currentIndex);
    } else {
        QMessageBox::information(m_mainWindow, "打开文件",
                                 QString("正在打开文件: %1").arg(fileInfo.fileName()));
        m_mainWindow->showStatusMessage("已打开文件: " + fileInfo.fileName());
    }
}

void FileContextMenu::onCutTriggered()
{
    if (!m_currentIndex.isValid()) return;

    m_copiedPath = m_model->filePath(m_currentIndex);
    m_isCutOperation = true;
    m_mainWindow->showStatusMessage("已剪切: " + m_copiedPath);
}

void FileContextMenu::onCopyTriggered()
{
    if (!m_currentIndex.isValid()) return;

    m_copiedPath = m_model->filePath(m_currentIndex);
    m_isCutOperation = false;
    m_mainWindow->showStatusMessage("已复制: " + m_copiedPath);
}

void FileContextMenu::onPasteTriggered()
{
    //todo if+
    if (m_copiedPath.isEmpty() || !m_currentView) {
        return;
    }

    QModelIndex targetIndex = qobject_cast<QAbstractItemView*>(m_currentView)->rootIndex();
    QString targetPath = m_model->filePath(targetIndex);

    QFileInfo sourceInfo(m_copiedPath);
    QString newPath = targetPath + QDir::separator() + sourceInfo.fileName();

    bool success = false;
    if (m_isCutOperation) {
        success = QFile::rename(m_copiedPath, newPath);
        if (success) {
            m_copiedPath.clear();
            m_mainWindow->showStatusMessage("已移动: " + newPath);
        }
    } else {
        if (sourceInfo.isDir()) {
            QDir sourceDir(m_copiedPath);
            QDir targetDir(targetPath);

            if (!targetDir.exists(newPath)) {
                targetDir.mkpath(newPath);
            }

            QStringList files = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
            foreach (const QString &file, files) {
                QString srcFilePath = m_copiedPath + QDir::separator() + file;
                QString dstFilePath = newPath + QDir::separator() + file;

                if (QFileInfo(srcFilePath).isDir()) {
                    QDir().mkpath(dstFilePath);
                    // 递归复制子目录
                    QFile::copy(srcFilePath, dstFilePath);
                } else {
                    QFile::copy(srcFilePath, dstFilePath);
                }
            }
            success = true;
        } else {
            success = QFile::copy(m_copiedPath, newPath);
        }
        if (success) {
            m_mainWindow->showStatusMessage("粘贴成功: " + newPath);
        }
    }

    if (!success) {
        QMessageBox::warning(m_mainWindow, "操作失败", "无法执行粘贴操作");
    }
}

void FileContextMenu::onDeleteTriggered()
{
    if (!m_currentIndex.isValid()) return;

    QString filePath = m_model->filePath(m_currentIndex);
    QMessageBox::StandardButton reply = QMessageBox::question(m_mainWindow, "删除确认",
                                                              QString("确定要删除 %1 吗?").arg(filePath),
                                                              QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        bool success = false;
        QFileInfo fileInfo(filePath);
        if (fileInfo.isDir()) {
            success = QDir(filePath).removeRecursively();
        } else {
            success = QFile::remove(filePath);
        }
        if (success) {
            m_mainWindow->showStatusMessage("已删除: " + filePath);
        } else {
            QMessageBox::warning(m_mainWindow, "删除失败", "无法删除文件或文件夹");
        }
    }
}

void FileContextMenu::onRenameTriggered()
{
    if (!m_currentIndex.isValid()) return;

    QString oldPath = m_model->filePath(m_currentIndex);
    QFileInfo fileInfo(oldPath);
    QString oldName = fileInfo.fileName();

    bool ok;
    QString newName = QInputDialog::getText(m_mainWindow, "重命名",
                                            "输入新名称:", QLineEdit::Normal,
                                            oldName, &ok);

    if (ok && !newName.isEmpty()) {
        QString newPath = fileInfo.path() + QDir::separator() + newName;
        bool success = QFile::rename(oldPath, newPath);
        if (success) {
            m_mainWindow->showStatusMessage("已重命名: " + oldName + " 为 " + newName);
        } else {
            QMessageBox::warning(m_mainWindow, "重命名失败", "无法重命名文件或文件夹");
        }
    }
}

void FileContextMenu::onNewFolderTriggered()
{
    if (!m_currentView) return;
    QAbstractItemView* view = qobject_cast<QAbstractItemView*>(m_currentView);
    QModelIndex targetIndex = view->rootIndex();
    QString targetPath = m_model->filePath(targetIndex);
    bool ok;
    QString folderName = QInputDialog::getText(m_mainWindow, "新建文件夹",
                                               "请输入文件夹名称:", QLineEdit::Normal,
                                               "新建文件夹", &ok);
    if (!ok || folderName.isEmpty()) {
        return;
    }
    QString newFolderPath = targetPath + QDir::separator() + folderName;
    int counter = 1;
    QString finalFolderName = folderName;
    while (QFileInfo(newFolderPath).exists()) {
        finalFolderName = QString("%1 (%2)").arg(folderName).arg(counter);
        newFolderPath = targetPath + QDir::separator() + finalFolderName;
        counter++;
    }
    bool success = QDir().mkdir(newFolderPath);
    if (success) {
        m_mainWindow->showStatusMessage("已创建新文件夹: " + finalFolderName);
        QModelIndex newFolderIndex = m_model->index(newFolderPath);
        if (newFolderIndex.isValid()) {
            view->setCurrentIndex(newFolderIndex);
        }
    } else {
        QMessageBox::warning(m_mainWindow, "创建失败", "无法创建新文件夹");
    }
}




void FileContextMenu::onPropertiesTriggered()
{
    if (!m_currentIndex.isValid()) return;

    QString filePath = m_model->filePath(m_currentIndex);
    QFileInfo fileInfo(filePath);

    // 兼容Qt 5.14，使用birthTime()替代已弃用的created()
    QString info = QString("名称: %1\n类型: %2\n路径: %3\n大小: %4 bytes\n创建时间: %5\n修改时间: %6")
                   .arg(fileInfo.fileName())
                   .arg(fileInfo.isDir() ? "文件夹" : "文件")
                   .arg(filePath)
                   .arg(fileInfo.size())
                   .arg(fileInfo.birthTime().toString("yyyy-MM-dd hh:mm:ss"))
                   .arg(fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss"));

    QMessageBox::information(m_mainWindow, "属性", info);
}

